package com.maxmlr.music.base;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maxmlr.music.bean.ResultBean;
import com.maxmlr.music.bean.ResultPageBean;
import com.maxmlr.music.constant.InterConstant;
import com.maxmlr.mybatisplus.base.BaseService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.Serializable;
import java.util.Optional;


/**
 * @author max
 * @version 1.0
 * @Package com.maxmlr.common.base
 * @ClassName BaseController
 * @Description 控制器基类
 * @Copyright Copyright (c) 2018: www.maxmlr.com.
 * @since 2018年12月15日 下午6:06:33
 */
public abstract class BaseController<M extends BaseService<T>, T> {

    @Autowired
    protected M baseService;

    protected ResultBean getResultBean(Object data) {
        return new ResultBean(data);
    }

    protected ResultPageBean getResultPageBean(Page<?> page) {
        return new ResultPageBean(page);
    }

    protected ResultBean getResultBean(long code, String msg) {
        return new ResultBean(code, msg);
    }

    protected ResultPageBean getResultPageBean(long code, String msg) {
        return new ResultPageBean(code, msg);
    }

    /**
     * @Description 获取分页列表
     * @author max
     * @since 2019-05-11
     */
    @RequestMapping("/getPageList")
    @ApiOperation(value = "/getPageList", notes = "获取分页列表")
    public ResultPageBean getPageList(@ApiParam(name = "param", value = "实体类") T param,
                                      @ApiParam(name = "pageSize", value = "页大小", required = true, defaultValue = "10") String pageSize,
                                      @ApiParam(name = "pageNum", value = "页数", required = true, defaultValue = "1") String pageNum) {
        Integer pageNumInt = Optional.ofNullable(pageNum).map(p -> Integer.valueOf(p)).orElse(InterConstant.pageNum);
        Integer pageSizeInt = Optional.ofNullable(pageSize).map(p -> Integer.valueOf(p)).orElse(InterConstant.pageSize);
        Page<T> page = new Page(pageNumInt, pageSizeInt);
        baseService.selectPageWithParam(page, param);
        return getResultPageBean(page);
    }

    /**
     * @Description 通过id获取Param
     * @author max
     * @since 2019-05-11
     */
    @RequestMapping("/getParamById")
    @ApiOperation(value = "/getParamById", notes = "通过id获取Param")
    public ResultBean getParamById(@ApiParam(name = "id", value = "ParamID", required = true) Serializable id) {
        T param = baseService.selectOneByObj(id);
        return getResultBean(param);
    }

}
